<script setup lang="ts">
import { useControllerStore } from '@/store';
import useModal from '@/hooks/useModal';
import usePlayAudio from '@/hooks/usePlayAudio';
import eventBus from '@/utils/eventBus';

interface IProps {
  data: IGoodsAdditionalInfo;
}

type EmitEvents = {
  (event: 'change', payload: { value: string }): void;
};

const props = defineProps<IProps>();
const emits = defineEmits<EmitEvents>();
const { showModal } = useModal();
const recordingTempFilePath = ref<string>(props.data.value);
const { isPlaying, playAudio, stopAudio } = usePlayAudio();
const randomNumber = Date.now() + Math.random().toString(36).substring(2);

onUnmounted(() => {
  unsubscribe();
});

// store监听
const unsubscribe = useControllerStore().$subscribe((_, storeState) => {
  if (storeState.recordingTempFilePath.find((item) => item.key === randomNumber)) {
    recordingTempFilePath.value = storeState.recordingTempFilePath.find((item) => item.key === randomNumber)!.value;
    emits('change', { value: recordingTempFilePath.value });
  }
});

// 处理录音长按事件
const handleRecordingLongPress = () => {
  uni.authorize({
    scope: 'scope.record',
    success: () => {
      eventBus.emit('callRecordingModal', { visible: true, text: '确认', key: randomNumber });
    },
    fail: () => {
      showModal(
        '需要获取您的录音权限，请前往设置中授权',
        {
          success: (res) => {
            if (res.confirm) uni.openSetting();
          },
        },
        '请求录音权限',
      );
    },
  });
};

// 重新录音
const handleReRecord = () => {
  recordingTempFilePath.value = '';
  emits('change', { value: '' });
};
</script>

<template>
  <van-cell :title="props.data.attrName" :required="props.data.requiredFlag">
    <view class="text-align-left">
      <view v-if="!recordingTempFilePath" class="c-br c-bg flex justify-center items-center text-white py-4px c-text-12" @longpress="handleRecordingLongPress">长按录音</view>
      <view v-else class="flex justify-between">
        <view v-if="!isPlaying" class="c-br c-bg flex justify-center items-center text-white py-4px flex-1 c-text-12" @click="playAudio(recordingTempFilePath)">播放录音</view>
        <view v-else class="c-br c-bg-sec flex justify-center items-center text-white py-4px flex-1 c-text-12" @click="stopAudio">停止播放</view>
        <view v-if="!isPlaying" class="c-br c-bg-sec flex justify-center items-center text-white py-4px flex-1 c-text-12 ml-2px" @click="handleReRecord">重新录音</view>
      </view>
    </view>
  </van-cell>
</template>
